// Copyright (C) 1998-2008, Sumisho Computer Systems Corp. All Rights Reserved.

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// 
//     http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @author Hitoshi Okada
 */

package com.curlap.orb.servlet;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.ServletException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.curlap.orb.security.AccessControlFilter;

/**
 * DestroyInstanceServlet
 */
public class DestroyInstanceServlet extends InstanceManagementServlet
{
	private static final long serialVersionUID = 1L;

    private final Log log = LogFactory.getLog(DestroyInstanceServlet.class);
    
    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException
    {
        super.doPost(request, response);
        final DestroyInstanceRequest destroyInstanceRequest = 
            (DestroyInstanceRequest)request.getAttribute(InstanceManagementServlet.REQUEST_OBJECT);
        try
        {
            final CurlConfig config = (CurlConfigFactory.getInstance(getServletContext())).getCurlConfig();
            if (!config.enabledHttpSessionMethod())
                throw new InstanceManagementException("HttpSession method is disabled.");

            final HttpSession session = request.getSession(false);
            final String objectId = destroyInstanceRequest.getObjectId();
            final Object obj = session.getAttribute(objectId);
            // - Security - access control
            (AccessControlFilter.getInstance(config.getAccessControlList())).checkAccessControlList(obj.getClass().getName());
            
            // remove the object from session
            session.removeAttribute(objectId);
            request.setAttribute(InstanceManagementServlet.RESPONSE_OBJECT, null);

            // debug
            log.debug("Request destroy [" + destroyInstanceRequest.getObjectId() + "]");
        }
        // IOException, SerializerException, InstanceManagementException
        catch (Exception e)
        {
            request.setAttribute(InstanceManagementServlet.RESPONSE_OBJECT, e);
        }
    }
}
